package com.guigu.controller.stock;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.guigu.pojo.design.DFile;
import com.guigu.pojo.manufacture.MManufacture;
import com.guigu.pojo.manufacture.MProcedure;
import com.guigu.pojo.manufacture.MProcedureModule;
import com.guigu.pojo.stock.SCell;
import com.guigu.pojo.stock.SPay;
import com.guigu.pojo.stock.SPayDetails;
import com.guigu.pojo.stock.SThirdProductArea;
import com.guigu.service.design.DFileService;
import com.guigu.service.manufacture.MManufactureService;
import com.guigu.service.manufacture.MProcedureModuleService;
import com.guigu.service.manufacture.MProcedureService;
import com.guigu.service.stock.SCellService;
import com.guigu.service.stock.SPayDetailsService;
import com.guigu.service.stock.SPayService;
import com.guigu.service.stock.SThirdProductAreaService;
import com.guigu.utils.CodeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Mr.Zhang
 * @since 2024-12-06
 */
@Controller
@RequestMapping("/s-pay")
public class SPayController {

    @Autowired
    private SPayService spayservice;

    @Autowired
    private DFileService dFileService;

    @Autowired
    private SCellService sCellService;

    @Autowired
    private SThirdProductAreaService sThirdProductAreaService;

    @Autowired
    private MManufactureService mManufactureService;

    @Autowired
    private MProcedureService mProcedureService;

    @Autowired
    private MProcedureModuleService mProcedureModuleService;

    @Autowired
    private SPayDetailsService spayDetailsService;

    //出库申请登记
    @GetMapping("/WarehouseOutApplicationRegistration")
    public String goWarehouseOutApplicationRegistration() {
        return "/jsp/stock/d/Warehouse-out_Application_Registration";
    }
    @GetMapping("/WarehouseOutApplicationRegistrationPreview")
    public String goWarehouseOutApplicationRegistrationPreview() {
        return "/jsp/stock/d/Warehouse-out_Application_Registration_preview";
    }
    //出库申请审核
    @GetMapping("/WarehouseOutApplicationReview")
    public String goWarehouseOutApplicationReview() {
        return "/jsp/stock/d/Warehouse-out_Application_review";
    }

    //出库申请审核子页面
    @GetMapping("/WarehouseOutApplicationReviewSub")
    public String goWarehouseOutApplicationReviewSub() {
        return "/jsp/stock/d/Warehouse-out_Application_review_sub";
    }

    //出库申请查询
    @GetMapping("/InquiryWarehouseOutApplicationRequery")
    public String goSPay() {
        return "/jsp/stock/d/Inquiry_Warehouse-out_Application_requery";
    }
    //出库申请查询
    @GetMapping("/Inquiry_Warehouse-out_Application")
    public String goInquiryWarehouseOutApplication(){
        return "/jsp/stock/d/Inquiry_Warehouse-out_Application";
    }
    //制定出库单查询
    @GetMapping("/Formulat_Prepare_delivery_order")
    public String goFormulatePrepareDeliveryOrder(){
        return "/jsp/stock/g/Formulate_Prepare_delivery_order";
    }
    //制定出库单
    @GetMapping("/Prepare_delivery_order")
    public String goFormulatePrepareWarehouseEntry(){
        return "/jsp/stock/g/Prepare_delivery_order";
    }

    //出库登记
    @GetMapping("/Warehouse-out_Registration")
    public String goWarehouseOutRegistration(){
        return "/jsp/stock/i/Warehouse-out_Registration";
    }
    @GetMapping("/Warehouse-out_Registration_sub")
    public String goWarehouseOutRegistrationSub(){
        return "/jsp/stock/i/Warehouse-out_Registration_sub";
    }

    //出库登记审核
    @GetMapping("/Warehouse-out_Registration_review")
    public String goWarehouseOutRegistrationReview(){
        return "/jsp/stock/i/Warehouse-out_Registration_review";
    }
    @GetMapping("/Warehouse-out_Registration_review_sub")
    public String goWarehouseOutRegistrationReviewSub(){
        return "/jsp/stock/i/Warehouse-out_Registration_review_sub";
    }
    //出库查询
    @GetMapping("/Inquiry_Warehouse-out")
    public String goInquiryWarehouseOut(){
        return "/jsp/stock/i/Inquiry_Warehouse-out";
    }
    @GetMapping("/Inquiry_Warehouse-out_requery")
    public String goInquiryWarehouseOutRequery(){
        return "/jsp/stock/i/Inquiry_Warehouse-out_requery";
    }

    //添加出库表和出库明细表
    //出库申请审核
    @PostMapping("/registration")
    @ResponseBody
    public Boolean registration(@RequestBody ArrayList<Object> data){
        System.out.println(data);
        //出库人
        String outbound ="";
        //出库理由
        String reason ="";
        //总件数
        BigDecimal totalNum = BigDecimal.valueOf(0L);
        //总金额
        BigDecimal totalPrice = BigDecimal.valueOf(0L);
        //登记时间
        String registerTime = "";
        //登记人
        String register = "";
        //备注
        String remark = "";
        //拿到第一个集合
        HashMap<String, Object> map = (HashMap<String, Object>) data.get(0);

        if(map.get("outbound")!=null){
            outbound = map.get("outbound").toString();
        }
        if(map.get("reason")!=null){
            reason = map.get("reason").toString();
        }
        if(map.get("totalNum")!=null){
            totalNum = BigDecimal.valueOf(Long.parseLong(map.get("totalNum").toString()));
        }
        if(map.get("totalPrice")!=null){
            totalPrice =BigDecimal.valueOf(Long.parseLong(map.get("totalPrice").toString()));
        }
        if(map.get("registerTime")!=null){
            registerTime = map.get("registerTime").toString();
        }
        if(map.get("register")!=null){
            register = map.get("register").toString();
        }
        if(map.get("remark")!=null){
            remark = map.get("remark").toString();
        }
        //获取出库明细表
        ArrayList<SPayDetails> details = new ArrayList<>();
        for (int i = 1; i < data.size(); i++) {
            HashMap<String, Object> map1 = (HashMap<String, Object>) data.get(i);
            SPayDetails spaydetails = new SPayDetails();
            spaydetails.setParentId(null);
            spaydetails.setProductId(map1.get("productId").toString());
            spaydetails.setProductName(map1.get("productName").toString());
            spaydetails.setProductDescribe(map1.get("productDescribe").toString());
            spaydetails.setAmount(BigDecimal.valueOf(Long.parseLong(map1.get("num").toString())));
            spaydetails.setAmountUnit(map1.get("amountUnit").toString());
            spaydetails.setCostPrice(BigDecimal.valueOf(Long.parseLong(map1.get("costPrice").toString())));
            spaydetails.setSubtotal(BigDecimal.valueOf(Long.parseLong(map1.get("total").toString())));
            spaydetails.setPaidAmount(BigDecimal.valueOf(0));
            spaydetails.setPayTag("0");
            details.add(spaydetails);
        }
        SPay spay = new SPay();
        SPay endSpay = spayservice.getEndSpay();
        CodeUtils codeUtils = new CodeUtils();
        String outboundCode = codeUtils.getOutboundCode(endSpay);

        spay.setPayId(outboundCode);
        spay.setStorer(outbound);
        spay.setReason(reason);
        spay.setReasonexact(null);
        spay.setAmountSum(totalNum);
        spay.setCostPriceSum(totalPrice);
        spay.setPaidAmountSum(BigDecimal.valueOf(0L));
        spay.setRemark(remark);
        spay.setRegister(register);
        spay.setRegisterTime(new Date());
        spay.setChecker(null);
        spay.setCheckTime(null);
        spay.setCheckTag("0");
        spay.setAttemper(null);
        spay.setAttemperTime(null);
        spay.setStoreTag("1");
        spay.setPayCheckTag("0");

        int id = spayservice.addSpay(spay);
        boolean b=false;
        for(SPayDetails sPayDetails:details){
            sPayDetails.setParentId(id);
             b = spayDetailsService.save(sPayDetails);
        }

        return b;
    }

    //查询出库申请登记(未审核的出库申请)
    @PostMapping("/initialOutboundTable")
    @ResponseBody
    public PageInfo<SPay> initialOutboundTable(@RequestBody HashMap<String, Object> map) {

        PageInfo<SPay> sPayPageInfo = spayservice.selectSpayByPage(map);
        return sPayPageInfo;
    }

    //根据id查询出库申请表(未审核的出库申请)
    @GetMapping("/ItemApprovalTable")
    @ResponseBody
    public SPay ItemApprovalTable(HttpServletRequest req){
        Integer id = StringUtils.isNotBlank(req.getParameter("id")) ? Integer.parseInt(req.getParameter("id")) : null;
        QueryWrapper<SPay> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        SPay sPay = spayservice.getOne(queryWrapper);
        return sPay;
    }

    //根据parentId查询出库明细表
    @GetMapping("/initialTemplate")
    @ResponseBody
    public ArrayList<SPayDetails> initialTemplate(HttpServletRequest req){
        Integer id = StringUtils.isNotBlank(req.getParameter("id")) ? Integer.parseInt(req.getParameter("id")) : null;
        ArrayList<SPayDetails> sPayDetails = spayDetailsService.selectArrByParentId(id);
        return sPayDetails;
    }

    //根据productId查询产品档案,在从产品档案获取三级分类Id查询库房表
    @GetMapping("/initialStoreroomTable")
    @ResponseBody
    public ArrayList<SThirdProductArea> initialStoreroomTable(HttpServletRequest req){
        String productId = req.getParameter("id");
        DFile dFile = dFileService.selectByProductId(productId);
        String thirdKindId = dFile.getThirdKindId();
        if(thirdKindId!=null){
            ArrayList<SThirdProductArea> sThirdProductAreas = sThirdProductAreaService.selectThird(thirdKindId);
            return sThirdProductAreas;
        }

        return null;
    }

    @PostMapping("/initialAmount")
    @ResponseBody
    public HashMap<String, SCell> initialAmount(@RequestBody String productIdStr){
        SCell sCell = sCellService.selectProductId(productIdStr);
        HashMap<String, SCell> resultMap = new HashMap<>();
        resultMap.put("sCell", sCell);
        return resultMap;
    }

    //根据条件查询出库表
    @PostMapping("/initialArchiveTable")
    @ResponseBody
    public PageInfo<SPay> initialArchiveTable(@RequestBody HashMap<String, Object> map) {
        PageInfo<SPay> sPayPage = spayservice.selectSpayByPage(map);
        return sPayPage;
    }


    @PostMapping("/dispatch")
    @ResponseBody
    public Boolean dispatch(@RequestBody ArrayList<Object> data){
        //拿到第一个集合
        HashMap<String, Object> map = (HashMap<String, Object>) data.get(0);
        //出库编号
        Integer id =0;
        //出库详情理由
        String productDescribe="";
        //出库单编号
        String payId ="";
        //出库产品编号
        String productId ="";
        //出库数量
        String num ="";
        if(map.get("id")!=null){
            id =Integer.parseInt(map.get("id").toString());
        }
        if(map.get("productDescribe")!=null){
            productDescribe =map.get("productDescribe").toString();
        }
        if(map.get("payId")!=null){
            payId = map.get("payId").toString();
        }
        if(map.get("productId")!=null){
            productId = map.get("productId").toString();
        }
        if(map.get("num")!=null){
            num = map.get("num").toString();
        }


        //修改出库明细表
        SPayDetails sPayDetails = new SPayDetails();
        sPayDetails.setParentId(id);
        sPayDetails.setProductId(productId);
        sPayDetails.setPayTag("2");
        boolean b = spayDetailsService.updateSpayDetails(sPayDetails);
        boolean flag = spayDetailsService.selectParentId(id, "0");

        if(!flag){
            //修改出库表
            SPay spay = new SPay();
            spay.setPayId(payId);
            spay.setStoreTag("2");
            boolean b2 = spayservice.updateSpay(spay);
        }
        return b;
    }

    //出库登记
    @PostMapping("/OutboundRegistration")
    @ResponseBody
    public Boolean OutboundRegistration(@RequestBody ArrayList<Object> data){
        //拿到第一个集合
        HashMap<String, Object> map = (HashMap<String, Object>) data.get(0);
        //出库单编号
        String payId ="";
        BigDecimal paidAmountSum=BigDecimal.valueOf(0L);
        if(map.get("payId")!=null){
            payId = map.get("payId").toString();
        }
        if(map.get("payId")!=null){
            paidAmountSum = BigDecimal.valueOf(Long.valueOf(map.get("paidAmountSum").toString()));
        }

        SPay spay = new SPay();
        spay.setPayId(payId);
        spay.setStoreTag("3");
        spay.setPaidAmountSum(paidAmountSum);
        spay.setPayCheckTag("1");
        spayservice.updateSpay(spay);
        //根据出库单编号查询出库表主键
        int id = spayservice.findBySpayId(payId);
        //获取出库明细表
        ArrayList<SPayDetails> details = new ArrayList<>();
        for(int i=1;i<data.size();i++){
            HashMap<String, Object> map1 = (HashMap<String, Object>) data.get(i);
            SPayDetails sPayDetails = new SPayDetails();
            sPayDetails.setParentId(id);
            sPayDetails.setProductId(map1.get("productId").toString());
            sPayDetails.setPaidAmount(BigDecimal.valueOf(Long.valueOf(map1.get("paidAmount").toString())));
            details.add(sPayDetails);
        }
        boolean b=false;
        for(SPayDetails sPayDetails:details){
            b = spayDetailsService.updateSpayDetails(sPayDetails);
        }
        return  b;
    }
    //出库审核
    @PostMapping("/OutboundRecheck")
    @ResponseBody
    public Boolean OutboundRecheck(@RequestBody ArrayList<Object> data){
        //拿到第一个集合
        HashMap<String, Object> map = (HashMap<String, Object>) data.get(0);
        //出库单编号
        String payId ="";
        BigDecimal paidAmountSum=BigDecimal.valueOf(0L);
        String reasonexact="";
        if(map.get("payId")!=null){
            payId = map.get("payId").toString();
        }
        if(map.get("paidAmountSum")!=null){
            paidAmountSum = BigDecimal.valueOf(Long.valueOf(map.get("paidAmountSum").toString()));
        }
        if(map.get("reasonexact")!=null){
            reasonexact =map.get("reasonexact").toString();

        }
        if(reasonexact.contains("-")){
            reasonexact = reasonexact.split("-")[0];
        }
        MManufacture manufacture = mManufactureService.getManufactureByManufactureId(reasonexact);
        List<MProcedure> procedureList = mProcedureService.getProcedureList(manufacture.getId());
        for (MProcedure procedure : procedureList){
            if (procedure.getDemandAmount()==null||BigDecimal.valueOf(0L).equals(procedure.getDemandAmount())){
                continue;
            }
            MProcedure procedure1=procedure;
            List<MProcedureModule> MProcedureModuleList = mProcedureModuleService.getProcedureModuleByParentId(procedure1.getId());
            for (MProcedureModule mProcedureModule : MProcedureModuleList){
                mProcedureModule.setRenewAmount(mProcedureModule.getAmount());
                mProcedureModuleService.updateById(mProcedureModule);
            }
        }



        SPay spay = new SPay();
        spay.setPayId(payId);
        spay.setPayCheckTag("2");
        spayservice.updateSpay(spay);
        //根据出库单编号查询出库表主键
        int id = spayservice.findBySpayId(payId);
        //获取出库明细表
        ArrayList<SPayDetails> details = new ArrayList<>();
        for(int i=1;i<data.size();i++){
            HashMap<String, Object> map1 = (HashMap<String, Object>) data.get(i);
            SPayDetails sPayDetails = new SPayDetails();
            sPayDetails.setParentId(id);
            sPayDetails.setProductId(map1.get("productId").toString());
            sPayDetails.setPaidAmount(BigDecimal.valueOf(Long.valueOf(map1.get("paidAmount").toString())));
            sPayDetails.setPayTag("3");
            details.add(sPayDetails);
        }
        boolean b=false;

        for(SPayDetails sPayDetails:details){
            b = spayDetailsService.updateSpayDetails(sPayDetails);
            //获取出库明细表的产品编号
            String productId = sPayDetails.getProductId();
            SCell sCell = sCellService.selectProductId(productId);
            BigDecimal amount = sCell.getAmount();
            Long amountnum=Long.parseLong(amount.toString());
            Long paidAmountnum =Long.parseLong(sPayDetails.getPaidAmount().toString());
            amount=BigDecimal.valueOf(amountnum-paidAmountnum);
            sCell.setProductId(productId);
            sCell.setAmount(amount);
            sCellService.updateProductId(sCell);



        }

        return  b;
    }
}

